using System;
using System.Collections.Generic;
using System.Text;

namespace BizTalkCop.Rules.Helpers
{
    /// <summary>
    /// Helper class for manipulating enum values
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// Parses the given string value into an enum of the given type
        /// </summary>
        /// <remarks>
        /// If the string value does not represent an enum value, the enum value 0 will be returned
        /// </remarks>
        /// <typeparam name="TEnum">Enum type</typeparam>
        /// <param name="value">String value</param>
        /// <returns>Enum value</returns>
        public static TEnum Parse<TEnum>(string value)
            where TEnum : struct, IComparable, IConvertible, IFormattable
        {
            TEnum enumValue;
            try
            {
                enumValue = (TEnum)Enum.Parse(typeof(TEnum), value, true);
            }
            catch (Exception ex)
            {
                //if the parse fails, set the enum to 0 (should be declared as Null):
                enumValue = (TEnum)Enum.Parse(typeof(TEnum), "0");
            }
            return enumValue;
        }
    }
}
